﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Web;
using System.Diagnostics;
using System.Globalization;

namespace AFT.Parking.Foundation.Extensions
{
    /// <summary>
    /// 字符串操作常用扩展
    /// </summary>
    /// <remarks>
    /// 编制人员 : 李侠[Justin]
    /// 完成时间 : 2010年04月21日
    /// 修改历史 : 无
    /// </remarks>
    public static class Strings
    {
        private static readonly Dictionary<int, string> _entityTable = new Dictionary<int, string>();
        private static readonly Dictionary<string, string> _USStateTable = new Dictionary<string, string>();
        private static readonly Regex WebUrlExpression = new Regex(@"([\w-]+\.)+[\w-]+.([^a-z])(/[\w-: ./?%&=]*)?|[a-zA-Z\-\.][\w-]+.([^a-z])(/[\w-: ./?%&=]*)?|(http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?", RegexOptions.Singleline | RegexOptions.Compiled);

        static Strings()
        {
            FillEntities();
            FillUSStates();
        }

        #region 分析Html字符串内href="url"的Url并为之进行编码，由子龙添加

        /// <summary>
        /// 分析Html字符串内href="url"的Url并为其中的参数进行编码替换，使用Utf-8编码
        /// </summary>
        /// <param name="text">要分析编码的的Html字符串</param>
        /// <returns>编码替换后的字符串</returns>
        public static string UrlEncodeReplace(this string text)
        {
            return text.UrlEncodeReplace(Encoding.GetEncoding("utf-8"));
        }

        /// <summary>
        /// 分析Html字符串内href="url"的Url并为其中的参数进行编码替换
        /// </summary>
        /// <param name="text">要分析编码的的Html字符串</param>
        /// <param name="e">编码类型</param>
        /// <returns>编码替换后的字符串</returns>
        public static string UrlEncodeReplace(this string text, System.Text.Encoding e)
        {
            string pattern = "href[\\s]*?=[\\s]*?\"(?<url>[\\s\\S]*?)\"";

            Regex re = new Regex(pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase);
            StringBuilder sb = new StringBuilder();
            if (re.IsMatch(text))
            {
                MatchCollection ms = re.Matches(text);
                int idx = 0;
                foreach (Match m in ms)
                {
                    //Regex reUrl = new Regex(@"", RegexOptions.Singleline | RegexOptions.IgnoreCase);
                    string s = m.Groups["url"].Value;
                    sb.Append(text.Substring(idx, m.Index - idx));
                    if (!s.IsNullOrEmpty())
                    {
                        s = UrlEncodeR(s, e);
                        sb.Append(text.Substring(m.Index, m.Groups["url"].Index - m.Index));
                        sb.Append(s);
                        if (m.Groups["url"].Index + m.Groups["url"].Length < m.Index + m.Length)
                            sb.Append(text.Substring(m.Groups["url"].Index + m.Groups["url"].Length,
                                m.Index + m.Length - m.Groups["url"].Index - m.Groups["url"].Length));
                    }
                    else
                    {
                        sb.Append(m.Value);
                    }
                    idx = m.Index + m.Length;
                }
                if (idx < text.Length)
                    sb.Append(text.Substring(idx));
            }
            else
            {
                return text;
            }
            return sb.ToString();
        }

        private static string UrlEncodeR(string url, Encoding e)
        {
            if (url.IsNullOrEmpty())
                return url;

            string s = url;
            string qStr = "";
            if (s.IndexOf("?") > -1)
            {
                StringBuilder sbQueryString = new StringBuilder();
                sbQueryString.Append("?");
                if (s.IndexOf("?") + 1 < s.Length)
                {
                    qStr = s.Substring(s.IndexOf("?") + 1);
                    var qArray = qStr.Split("&");
                    foreach (var p in qArray)
                    {
                        if (p.IndexOf("=") > -1)
                        {
                            sbQueryString.Append(p.Substring(0, p.IndexOf("=")));
                            sbQueryString.Append("=");
                            sbQueryString.Append(
                                (p.IndexOf("=") + 1 < s.Length) ?
                                System.Web.HttpUtility.UrlEncode(p.Substring(p.IndexOf("=") + 1), e) :
                                "");
                            sbQueryString.Append("&");
                        }
                    }
                }
                s = s.Substring(0, s.IndexOf("?")) + sbQueryString.ToString();
                s = s.Substring(0, s.Length - 1);
            }
            return s;
        }

        #endregion

        public static string AssemblyPath()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + @"Bin\";  // Web Site

            if (Environment.CurrentDirectory == AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\')) // Others
            {
                path = AppDomain.CurrentDomain.BaseDirectory;
            }

            if (Environment.CurrentDirectory.Equals(@"C:\WINDOWS\system32")) // Service
            {
                path = AppDomain.CurrentDomain.BaseDirectory;
            }

            return path;
        }

        /// <summary>
        /// 替换html中的特殊符号 
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string ReplaceSpecialSymbols(this string s)
        {
            s = s.Replace("&amp;", "&");
            s = s.Replace("&quot;", "“");
            s = s.Replace("&lt;", "<");
            s = s.Replace("&gt;", ">");
            s = s.Replace("&nbsp;", " ");
            s = s.Replace("&laquo;", "«");
            s = s.Replace("&raquo;", "»");
            s = s.Replace("&lsquo;", "‘");
            s = s.Replace("&rsquo;", "’");
            s = s.Replace("&ldquo;", "“");
            s = s.Replace("&rdquo;", "”");
            s = s.Replace("&sect;", "§");
            s = s.Replace("&copy;", "©");
            s = s.Replace("&hellip;", "…");
            s = s.Replace("&oplus;", "⊕");
            s = s.Replace("&nabla;", "∇");
            s = s.Replace("&times;", "×");
            s = s.Replace("&divide;", "÷");
            s = s.Replace("&plusmn;", "±");
            s = s.Replace("&radic;", "√");
            s = s.Replace("&infin;", "∞");
            s = s.Replace("&ang;", "∠");
            s = s.Replace("&int;", "∫");
            s = s.Replace("&deg;", "°");
            s = s.Replace("&ne;", "≠");
            s = s.Replace("&equiv;", "≡");
            s = s.Replace("&le;", "≤");
            s = s.Replace("&ge;", "≥");
            s = s.Replace("&perp;", "⊥");
            s = s.Replace("&there4;", "∴");
            s = s.Replace("&pi;", "π");
            s = s.Replace("&sup1;", "¹");
            s = s.Replace("&sup2;", "²");
            s = s.Replace("&sup3;", "³");
            s = s.Replace("&crarr;", "↵");
            s = s.Replace("&larr;", "←");
            s = s.Replace("&uarr;", "↑");
            s = s.Replace("&rarr;", "→");
            s = s.Replace("&darr;", "↓");
            s = s.Replace("&lArr;", "⇐");
            s = s.Replace("&uArr;", "⇑");
            s = s.Replace("&rArr;", "⇒");
            s = s.Replace("&dArr;", "⇓");
            s = s.Replace("&alpha;", "α");
            s = s.Replace("&beta;", "β");
            s = s.Replace("&gamma;", "γ");
            s = s.Replace("&Delta;", "Δ");
            s = s.Replace("&theta;", "θ");
            s = s.Replace("&lambda;", "λ");
            s = s.Replace("&Sigma;", "Σ");
            s = s.Replace("&tau;", "τ");
            s = s.Replace("&omega;", "ω");
            s = s.Replace("&Omega;", "Ω");
            s = s.Replace("&bull;", "•");
            s = s.Replace("<!--", "");
            s = s.Replace("-->", "");
            return s;
        }

        /// <summary>
        /// 截取包含中文、英文、中英文混合字符的字符串
        /// </summary>
        /// <param name="s"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static String bSubstring(this string s, int length)
        {
            if (s.GetLength() > length)
            {
                if (s == null || s.Length == 0 || length <= 0)
                {
                    return string.Empty;
                }

                int l = s.Length;

                #region 计算长度
                int clen = 0;
                while (clen < length && clen < l)
                {
                    //每遇到一个中文，则将目标长度减一。
                    if ((int)s[clen] > 128) { length--; }
                    clen++;
                }
                #endregion

                if (clen < l)
                {
                    return s.Substring(0, clen) + "...";
                }
                else
                {
                    return s;
                }
            }
            else
            {
                return s;
            }
        }

        /// <summary>
        /// 获取中文、英文、中英文混合字符串长度
        /// </summary>
        /// <param name="strSource"></param>
        /// <returns></returns>
        public static int GetLength(this string strSource)
        {
            return strSource.IsNullOrEmpty()?0:Encoding.GetEncoding("GB18030").GetBytes(strSource).Length;
        }

        /// <summary>
        /// 分割字符串为数组
        /// </summary>
        /// <param name="source">待分割的字符串</param>
        /// <param name="separator">分割字符</param>
        /// <returns>字符串数组</returns>
        public static string[] Split(this string source, string separator)
        {
            return source.Split(new string[] { separator }, StringSplitOptions.None);
        }

        /// <summary>
        /// 检查该字符串是否为空
        /// </summary>
        /// <param name="source">待检查字符串</param>
        /// <returns>如果为Null或者string.Empty则为true 否则false</returns>
        public static bool IsNullOrEmpty(this string source)
        {
            return string.IsNullOrEmpty(source);
        }

        /// <summary>
        /// 半角转全角
        /// </summary>
        /// <param name="source">待转换字符串</param>
        /// <returns>全角字符串</returns>
        ///<remarks>
        ///全角空格为12288，半角空格为32
        ///其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248
        ///</remarks>
        public static string ToSBC(this string source)
        {
            //半角转全角：
            char[] c = source.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 32)
                {
                    c[i] = (char)12288;
                    continue;
                }
                if (c[i] < 127)
                    c[i] = (char)(c[i] + 65248);
            }
            return new string(c);
        }

        /// <summary>
        /// 全角转半角
        /// </summary>
        /// <param name="input">待转换字符串</param>
        /// <returns>半角字符串</returns>
        ///<remarks>
        ///全角空格为12288，半角空格为32
        ///其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248
        ///</remarks>
        public static string ToDBC(this string source)
        {
            char[] c = source.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 12288)
                {
                    c[i] = (char)32;
                    continue;
                }
                if (c[i] > 65280 && c[i] < 65375)
                    c[i] = (char)(c[i] - 65248);
            }
            return new string(c);
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        public static string MD5Decrypt(this string source)
        {
            byte[] buffer = System.Text.Encoding.Default.GetBytes(source);
            try
            {
                System.Security.Cryptography.MD5CryptoServiceProvider check;
                check = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] somme = check.ComputeHash(buffer);
                string ret = "";
                foreach (byte a in somme)
                {
                    if (a < 16)
                        ret += "0" + a.ToString("X");
                    else
                        ret += a.ToString("X");
                }
                return ret.ToLower();
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 将字符串超过指定长度的部分截断,中文按2位,英文1位
        /// </summary>
        /// <param name="source">待截断的字符串</param>
        /// <param name="length">长度</param>
        /// <returns>返回指定长度的部分</returns>
        public static string Cutstring(this string source, int length)
        {
            if (string.IsNullOrEmpty(source))
                return source;

            byte[] bytesOfSource = System.Text.Encoding.Default.GetBytes(source);

            if (length > bytesOfSource.Length)
                return source;

            Regex reg = new Regex("[^\x00-\xff]+", RegexOptions.Compiled);

            char[] charsOfSource = source.ToCharArray();

            StringBuilder resultBuilder = new StringBuilder();

            int index = 0;

            for (int i = 0; i < charsOfSource.Length; i++)
            {
                if (reg.IsMatch(charsOfSource[i].ToString()))
                {
                    if (length - index > 1)
                    {
                        resultBuilder.Append(charsOfSource[i]);
                    }

                    index += 2;
                }
                else
                {
                    resultBuilder.Append(charsOfSource[i]);

                    index = index + 1;
                }

                if (index >= length)
                    break;
            }

            return resultBuilder.ToString();
        }

        /// <summary>
        /// 清除UBB代码
        /// </summary>
        public static string RemoveUBBCode(this string content, int page, int preview)
        {
            string[] ubbKeys = new string[] { "center", "left", "right", "fleft", "fright", "fright" };
            foreach (string ubbKey in ubbKeys)
            {
                content = content.RegexReplace(@"(\[" + ubbKey + @"\])", "");
                content = content.RegexReplace(@"(\[\/" + ubbKey + @"\])", "");
            }

            content = content.RegexReplace("(script)", "s cript");

            ubbKeys = new string[] { "DIR", "QT", "MP", "RM" };
            foreach (string ubbKey in ubbKeys)
            {
                content = content.RegexReplace(@"\[" + ubbKey + @"=*([0-9]*),*([0-9]*)\](.[^\[]*)\[\/" + ubbKey + @"]", "");
            }

            content = content.RegexReplace(@"(\[UPLOAD=(.[^\[]*)\])(.[^\[]*)(\[\/UPLOAD\])", "");

            ubbKeys = new string[] { "IMG", "FLASH", "UPLOAD" };
            foreach (string ubbKey in ubbKeys)
            {
                content = content.RegexReplace(@"(\[" + ubbKey + @"\])(.[^\[]*)(\[\/" + ubbKey + @"\])", "");
            }

            string[] patterns = new string[] { @"(\[URL\])(.[^\[]*)(\[\/URL\])", @"(\[URL=(.[^\[]*)\])(.[^\[]*)(\[\/URL\])" };
            foreach (string pattern in patterns)
            {
                content = content.RegexReplace(pattern, @"<A HREF=""$2\"" TARGET=_blank>$3</A>");
            }

            patterns = new string[] { @"(\[EMAIL\])(.[^\[]*)(\[\/EMAIL\])", @"(\[EMAIL=(.[^\[]*)\])(.[^\[]*)(\[\/EMAIL\])" };
            foreach (string pattern in patterns)
            {
                content = content.RegexReplace(pattern, @"<img align=absmiddle src=""/Images/Hqen/Order/tmail.gif""><A HREF=""mailto:$2"" TARGET=_blank>$3</A>");
            }

            ubbKeys = new string[] { "http", "ftp", "rtsp", "mms" };
            string patternStr = @"://[A-Za-z0-9\./=\?%\-&_~`@':+!]+)";
            string repStr = @"<a target=_blank href=$1>$1</a>";
            foreach (string ubbKey in ubbKeys)
            {
                content = content.RegexReplace(@"^(" + ubbKey + patternStr, repStr);
                content = content.RegexReplace(@"(" + ubbKey + patternStr + "$", repStr);
                content = content.RegexReplace(@"[^>=""](" + ubbKey + patternStr, repStr);
            }

            ubbKeys = new string[] { "color", "face" };
            foreach (string ubbKey in ubbKeys)
            {
                content = content.RegexReplace(@"(\[" + ubbKey + @"=(.[^\[]*)\])(.[^\[]*)(\[\/" + ubbKey + @"\])", "$3");
            }

            content = content.RegexReplace(@"(\[align=(.[^\[]*)\])(.*)(\[\/align\])", "$3");

            ubbKeys = new string[] { "QUOTE", "fly", "move" };
            foreach (string ubbKey in ubbKeys)
            {
                repStr = "$2";
                if (ubbKey == "QUOTE")
                {
                    repStr = @"<table cellpadding=0 cellspacing=0 border=0 WIDTH=94% bgcolor=#000000 align=center><tr><td><table width=100% cellpadding=5 cellspacing=1 border=0><TR><TD>$2</table></table><br>";
                }
                content = content.RegexReplace(@"(\[" + ubbKey + @"\])(.*)(\[\/" + ubbKey + @"\])", repStr);
            }

            ubbKeys = new string[] { "GLOW", "SHADOW" };
            foreach (string ubbKey in ubbKeys)
            {
                content = content.RegexReplace(@"\[" + ubbKey + @"=*([0-9]*),*(#*[a-z0-9]*),*([0-9]*)\](.[^\[]*)\[\/" + ubbKey + @"]", "$4");
            }

            ubbKeys = new string[] { "i", "u", "b" };
            foreach (string ubbKey in ubbKeys)
            {
                content = content.RegexReplace(@"(\[" + ubbKey + @"\])(.[^\[]*)(\[\/" + ubbKey + @"\])", "$2");
            }

            for (int i = 1; i < 5; i++)
            {
                content = content.RegexReplace(@"(\[size=" + i.ToString() + @"\])(.[^\[]*)(\[\/size\])", "$2");
            }


            //分页处理
            if (preview == 1)
            {
                content = content.RegexReplace(@"\[page\]", "");
            }
            else
            {
                string[] splitStr = new string[] { @"\[page\]" };
                string[] contents = content.Split(splitStr, StringSplitOptions.RemoveEmptyEntries);
                if (page > contents.Length)
                {
                    page = contents.Length;
                }
                if (page < 0) page = 1;
                content = contents[page - 1];
            }
            return content;
        }

        /// <summary>
        /// 过滤HTML代码的函数包括过滤CSS和JS
        /// </summary>
        public static string RemoveHtmlTag(this string content)
        {
            if (string.IsNullOrEmpty(content))
                return string.Empty;

            return content.RegexReplace("<.+?>", "");

            //if (string.IsNullOrEmpty(content))
            //    return string.Empty;

            ////匹配<>中的内容,替换为空字符
            //Regex regex = new Regex("<.+?>");
            //MatchCollection matchCollection = regex.Matches(content);
            //foreach (Match match in matchCollection)
            //{
            //    content = content.Replace(match.Value, "");
            //}
            //return content;
        }

        /// <summary>
        /// 按正则表达式进行匹配替换
        /// </summary>
        public static string RegexReplace(this string content, string pattern, string replaceStr)
        {
            Regex regex = new Regex(pattern);

            content = regex.Replace(content, replaceStr);

            return content;
        }

        /// <summary>
        /// 替换掉特殊字符
        /// </summary>
        public static string ReplaceSpecialCharacter(this string source)
        {
            string replacePattern = @"[\+\|\-|\&|\!|\(|\)|\{|\}|\[|\]|\^|""|\~|\*|\|\?|\:|\\]+";

            return Regex.Replace(source, replacePattern, new MatchEvaluator(m => m.Value));
        }

        public static bool IsWebUrl(this string target)
        {
            return !string.IsNullOrEmpty(target) && WebUrlExpression.IsMatch(target);
        }

        /// <summary>
        /// 格式化成重写后的URL格式
        /// </summary>
        /// <param name="replaceStr">特殊字符替代字符</param>
        /// <returns>重写后的URL格式</returns>
        public static string FormatRewriteUrl(this string source, string replaceStr)
        {
            string[] aryReg = { "'", "<", ">", "%", "‰", "\"\"", ",", ".", ">=", "=<", "-", "_", ";", "||", "[", "]", "&", "/", "／", "-", "－", "|", "(", ")", "Ⅲ", "Ⅱ", "Ⅳ", "*", "×", "”", "~", "@", "#", "＃", "$", "^", "!", "\"", "+", "＋", "°", "℃", "㎡", ":", "；", "±", "≤", "≥", "＝", "≈", "↖", "↗", "↙", "↘", "←", "→", "￡" };
            for (int i = 0; i < aryReg.Length; i++)
            {
                source = source.Replace(aryReg[i], string.Empty);
            }
            return source.Replace(" ", replaceStr);
        }

        /// <summary>
        /// 判断字符串中是否包含1个以上中文字符
        /// </summary>
        public static bool IncludeChineseCharacter(this string source)
        {
            string pattern = @"[\u4e00-\u9fa5|\s]+";

            return Regex.IsMatch(source, pattern);
        }

        public static bool Matches(this string source, string compare)
        {
            return String.Equals(source, compare, StringComparison.InvariantCultureIgnoreCase);
        }

        public static bool MatchesTrimmed(this string source, string compare)
        {
            return String.Equals(source.Trim(), compare.Trim(), StringComparison.InvariantCultureIgnoreCase);
        }

        public static bool MatchesRegex(this string inputString, string matchPattern)
        {
            return Regex.IsMatch(inputString, matchPattern,
                RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
        }

        public static List<string> GetList(this string sInput, string sRegex, int iGroupIndex)
        {
            List<string> list = new List<string>();
            Regex re = new Regex(sRegex, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
            MatchCollection mcs = re.Matches(sInput);
            foreach (Match mc in mcs)
            {
                if (iGroupIndex > 0)
                    list.Add(mc.Groups[iGroupIndex].Value);
                else
                    list.Add(mc.Value);
            }
            return list;
        }

        /// <summary>
        /// Strips the last specified chars from a string.
        /// </summary>
        /// <param name="sourceString">The source string.</param>
        /// <param name="removeFromEnd">The remove from end.</param>
        /// <returns></returns>
        public static string Chop(this string sourceString, int removeFromEnd)
        {
            string result = sourceString;
            if ((removeFromEnd > 0) && (sourceString.Length > removeFromEnd - 1))
                result = result.Remove(sourceString.Length - removeFromEnd, removeFromEnd);
            return result;
        }

        /// <summary>
        /// Strips the last specified chars from a string.
        /// </summary>
        /// <param name="sourceString">The source string.</param>
        /// <param name="backDownTo">The back down to.</param>
        /// <returns></returns>
        public static string Chop(this string sourceString, string backDownTo)
        {
            int removeDownTo = sourceString.LastIndexOf(backDownTo);
            int removeFromEnd = 0;
            if (removeDownTo > 0)
                removeFromEnd = sourceString.Length - removeDownTo;

            string result = sourceString;

            if (sourceString.Length > removeFromEnd - 1)
                result = result.Remove(removeDownTo, removeFromEnd);

            return result;
        }

        /// <summary>
        /// Plurals to singular.
        /// </summary>
        /// <param name="sourceString">The source string.</param>
        /// <returns></returns>
        public static string PluralToSingular(this string sourceString)
        {
            return sourceString.MakeSingular();
        }

        /// <summary>
        /// Singulars to plural.
        /// </summary>
        /// <param name="sourceString">The source string.</param>
        /// <returns></returns>
        public static string SingularToPlural(this string sourceString)
        {
            return sourceString.MakePlural();
        }

        /// <summary>
        /// Make plural when count is not one
        /// </summary>
        /// <param name="number">The number of things</param>
        /// <param name="sourceString">The source string.</param>
        /// <returns></returns>
        public static string Pluralize(this int number, string sourceString)
        {
            if (number == 1)
                return String.Concat(number, " ", sourceString.MakeSingular());
            return String.Concat(number, " ", sourceString.MakePlural());
        }

        /// <summary>
        /// Removes the specified chars from the beginning of a string.
        /// </summary>
        /// <param name="sourceString">The source string.</param>
        /// <param name="removeFromBeginning">The remove from beginning.</param>
        /// <returns></returns>
        public static string Clip(this string sourceString, int removeFromBeginning)
        {
            string result = sourceString;
            if (sourceString.Length > removeFromBeginning)
                result = result.Remove(0, removeFromBeginning);
            return result;
        }

        /// <summary>
        /// Removes chars from the beginning of a string, up to the specified string
        /// </summary>
        /// <param name="sourceString">The source string.</param>
        /// <param name="removeUpTo">The remove up to.</param>
        /// <returns></returns>
        public static string Clip(this string sourceString, string removeUpTo)
        {
            int removeFromBeginning = sourceString.IndexOf(removeUpTo);
            string result = sourceString;

            if (sourceString.Length > removeFromBeginning && removeFromBeginning > 0)
                result = result.Remove(0, removeFromBeginning);

            return result;
        }

        /// <summary>
        /// Strips the last char from a a string.
        /// </summary>
        /// <param name="sourceString">The source string.</param>
        /// <returns></returns>
        public static string Chop(this string sourceString)
        {
            return Chop(sourceString, 1);
        }

        /// <summary>
        /// Strips the last char from a a string.
        /// </summary>
        /// <param name="sourceString">The source string.</param>
        /// <returns></returns>
        public static string Clip(this string sourceString)
        {
            return Clip(sourceString, 1);
        }

        /// <summary>
        /// Fasts the replace.
        /// </summary>
        /// <param name="original">The original.</param>
        /// <param name="pattern">The pattern.</param>
        /// <param name="replacement">The replacement.</param>
        /// <returns></returns>
        public static string FastReplace(this string original, string pattern, string replacement)
        {
            return FastReplace(original, pattern, replacement, StringComparison.InvariantCultureIgnoreCase);
        }

        /// <summary>
        /// Fasts the replace.
        /// </summary>
        /// <param name="original">The original.</param>
        /// <param name="pattern">The pattern.</param>
        /// <param name="replacement">The replacement.</param>
        /// <param name="comparisonType">Type of the comparison.</param>
        /// <returns></returns>
        public static string FastReplace(this string original, string pattern, string replacement,
                                         StringComparison comparisonType)
        {
            if (original == null)
                return null;

            if (String.IsNullOrEmpty(pattern))
                return original;

            int lenPattern = pattern.Length;
            int idxPattern = -1;
            int idxLast = 0;

            StringBuilder result = new StringBuilder();

            while (true)
            {
                idxPattern = original.IndexOf(pattern, idxPattern + 1, comparisonType);

                if (idxPattern < 0)
                {
                    result.Append(original, idxLast, original.Length - idxLast);
                    break;
                }

                result.Append(original, idxLast, idxPattern - idxLast);
                result.Append(replacement);

                idxLast = idxPattern + lenPattern;
            }

            return result.ToString();
        }

        /// <summary>
        /// Returns text that is located between the startText and endText tags.
        /// </summary>
        /// <param name="sourceString">The source string.</param>
        /// <param name="startText">The text from which to start the crop</param>
        /// <param name="endText">The endpoint of the crop</param>
        /// <returns></returns>
        public static string Crop(this string sourceString, string startText, string endText)
        {
            int startIndex = sourceString.IndexOf(startText, StringComparison.CurrentCultureIgnoreCase);
            if (startIndex == -1)
                return String.Empty;

            startIndex += startText.Length;
            int endIndex = sourceString.IndexOf(endText, startIndex, StringComparison.CurrentCultureIgnoreCase);
            if (endIndex == -1)
                return String.Empty;

            return sourceString.Substring(startIndex, endIndex - startIndex);
        }

        /// <summary>
        /// Removes excess white space in a string.
        /// </summary>
        /// <param name="sourceString">The source string.</param>
        /// <returns></returns>
        public static string Squeeze(this string sourceString)
        {
            char[] delim = { ' ' };
            string[] lines = sourceString.Split(delim, StringSplitOptions.RemoveEmptyEntries);
            StringBuilder sb = new StringBuilder();
            foreach (string s in lines)
            {
                if (!String.IsNullOrEmpty(s.Trim()))
                    sb.Append(s + " ");
            }
            //remove the last pipe
            string result = Chop(sb.ToString());
            return result.Trim();
        }

        /// <summary>
        /// Removes all non-alpha numeric characters in a string
        /// </summary>
        /// <param name="sourceString">The source string.</param>
        /// <returns></returns>
        public static string ToAlphaNumericOnly(this string sourceString)
        {
            return Regex.Replace(sourceString, @"\W*", "");
        }

        /// <summary>
        /// Creates a string array based on the words in a sentence
        /// </summary>
        /// <param name="sourceString">The source string.</param>
        /// <returns></returns>
        public static string[] ToWords(this string sourceString)
        {
            string result = sourceString.Trim();
            return result.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        }

        /// <summary>
        /// Strips all HTML tags from a string
        /// </summary>
        /// <param name="htmlString">The HTML string.</param>
        /// <returns></returns>
        //public static string StripHTML(this string htmlString)
        //{
        //    return StripHTML(htmlString, String.Empty);
        //}
        public static string StripHTML(string htmlString)
        {
            string[] aryReg ={
              @"<script[^>]*?>.*?</script>",

              @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(file://[""'tbnr]|[^/7])*?/7|/w+)|.{0})|/s)*?(///s*)?>",
              @"([\r\n])[\s]+",
              @"&(quot|#34);",
              @"&(amp|#38);",

              @"&(lt|#60);",
              @"&(gt|#62);", 
              @"&(nbsp|#160);", 
              @"&(iexcl|#161);",
              @"&(cent|#162);",
              @"&(pound|#163);",
              @"&(copy|#169);",
              @"&#(\d+);",
              @"-->",
              @"<!--.*\n"
         
             };

            string[] aryRep = {
               "",
               "",
               "",
               "\"",
               "&",
               "<",
               ">",
               " ",
               "\xa1",//chr(161),
               "\xa2",//chr(162),
               "\xa3",//chr(163),
               "\xa9",//chr(169),
               "",
               "\r\n",
               ""
              };

            string newReg = aryReg[0];
            string strOutput = htmlString;
            for (int i = 0; i < aryReg.Length; i++)
            {
                Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase);
                strOutput = regex.Replace(strOutput, aryRep[i]);
            }

            strOutput.Replace("<", "");
            strOutput.Replace(">", "");
            strOutput.Replace("\r\n", "");

            return strOutput;
        }

        /// <summary>
        /// Strips all HTML tags from a string and replaces the tags with the specified replacement
        /// </summary>
        /// <param name="htmlString">The HTML string.</param>
        /// <param name="htmlPlaceHolder">The HTML place holder.</param>
        /// <returns></returns>
        public static string StripHTML(this string htmlString, string htmlPlaceHolder)
        {
            const string pattern = @"<(.|\n)*?>";
            string sOut = Regex.Replace(htmlString, pattern, htmlPlaceHolder);
            sOut = sOut.Replace("&nbsp;", String.Empty);
            sOut = sOut.Replace("&amp;", "&");
            sOut = sOut.Replace("&gt;", ">");
            sOut = sOut.Replace("&lt;", "<");
            return sOut;
        }

        public static List<string> FindMatches(this string source, string find)
        {
            Regex reg = new Regex(find, RegexOptions.IgnoreCase);

            List<string> result = new List<string>();
            foreach (Match m in reg.Matches(source))
                result.Add(m.Value);
            return result;
        }

        public static string FindMatche(this string source, string find)
        {
            Regex re = new Regex(find, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
            Match mc = re.Match(source);
            if (mc.Success)
            {
                return mc.Value;
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// Converts a generic List collection to a single comma-delimitted string.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <returns></returns>
        public static string ToDelimitedList(this IEnumerable<string> list)
        {
            return ToDelimitedList(list, ",");
        }

        /// <summary>
        /// Converts a generic List collection to a single string using the specified delimitter.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <param name="delimiter">The delimiter.</param>
        /// <returns></returns>
        public static string ToDelimitedList(this IEnumerable<string> list, string delimiter)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string s in list)
                sb.Append(String.Concat(s, delimiter));
            string result = sb.ToString();
            result = Chop(result);
            return result;
        }

        /// <summary>
        /// Strips the specified input.
        /// </summary>
        /// <param name="sourceString">The source string.</param>
        /// <param name="stripValue">The strip value.</param>
        /// <returns></returns>
        public static string Strip(this string sourceString, string stripValue)
        {
            if (!String.IsNullOrEmpty(stripValue))
            {
                string[] replace = stripValue.Split(new[] { ',' });
                for (int i = 0; i < replace.Length; i++)
                {
                    if (!String.IsNullOrEmpty(sourceString))
                        sourceString = Regex.Replace(sourceString, replace[i], String.Empty);
                }
            }
            return sourceString;
        }

        /// <summary>
        /// Converts ASCII encoding to Unicode
        /// </summary>
        /// <param name="asciiCode">The ASCII code.</param>
        /// <returns></returns>
        public static string AsciiToUnicode(this int asciiCode)
        {
            Encoding ascii = Encoding.UTF32;
            char c = (char)asciiCode;
            Byte[] b = ascii.GetBytes(c.ToString());
            return ascii.GetString((b));
        }

        /// <summary>
        /// 字母转换为数字
        /// </summary>
        /// <param name="letter"></param>
        /// <returns></returns>
        public static int LetterToUnicode(this string letter)
        {
            byte[] array = new byte[1];   //定义一组数组array
            array = System.Text.Encoding.Unicode.GetBytes(letter); //string转换的字母
            int unicode = (short)(array[0]);
            return unicode;
        }

        /// <summary>
        /// Converts Text to HTML-encoded string
        /// </summary>
        /// <param name="textString">The text string.</param>
        /// <returns></returns>
        public static string TextTjson(this string textString)
        {
            foreach (KeyValuePair<int, string> key in _entityTable)
                textString = textString.Replace(AsciiToUnicode(key.Key), key.Value);
            return textString.Replace(AsciiToUnicode(38), "&amp;");
        }

        /// <summary>
        /// Converts HTML-encoded bits to Text
        /// </summary>
        /// <param name="entityText">The entity text.</param>
        /// <returns></returns>
        public static string EntityToText(this string entityText)
        {
            entityText = entityText.Replace("&amp;", "&");
            foreach (KeyValuePair<int, string> key in _entityTable)
                entityText = entityText.Replace(key.Value, AsciiToUnicode(key.Key));
            return entityText;
        }

        /// <summary>
        /// Formats the args using String.Format with the target string as a format string.
        /// </summary>
        /// <param name="fmt">The format string passed to String.Format</param>
        /// <param name="args">The args passed to String.Format</param>
        /// <returns></returns>
        public static string ToFormattedString(this string fmt, params object[] args)
        {
            return String.Format(fmt, args);
        }

        /// <summary>
        /// Strings to enum.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Value">The value.</param>
        /// <returns></returns>
        public static T ToEnum<T>(this string Value)
        {
            T oOut = default(T);
            Type t = typeof(T);
            foreach (FieldInfo fi in t.GetFields())
            {
                if (fi.Name.Matches(Value))
                    oOut = (T)fi.GetValue(null);
            }

            return oOut;
        }

        [DebuggerStepThrough]
        public static string UrlEncode(this string target)
        {
            return HttpUtility.UrlEncode(target);
        }

        [DebuggerStepThrough]
        public static string UrlDecode(this string target)
        {
            return HttpUtility.UrlDecode(target);
        }

        [DebuggerStepThrough]
        public static string AttributeEncode(this string target)
        {
            return HttpUtility.HtmlAttributeEncode(target);
        }

        [DebuggerStepThrough]
        public static string HtmlEncode(this string target)
        {
            return HttpUtility.HtmlEncode(target);
        }

        [DebuggerStepThrough]
        public static string HtmlDecode(this string target)
        {
            return HttpUtility.HtmlDecode(target);
        }

        [DebuggerStepThrough]
        public static string NullSafe(this string target)
        {
            return (target ?? string.Empty).Trim();
        }

        /// <summary>
        /// BASE64编码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string EncodeBase64ForUrl(this string str)
        {
            byte[] encbuff = System.Text.Encoding.UTF8.GetBytes(str);
            string base64string = Convert.ToBase64String(encbuff);
            base64string = base64string.Replace("+", "*");
            base64string = base64string.Replace("/", "-");
            return base64string;
        }

        /// <summary>
        /// BASE64解码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string DecodeBase64ForUrl(this string str)
        {
            str = str.Replace("*", "+");
            str = str.Replace("-", "/");
            byte[] decbuff = Convert.FromBase64String(str);
            return System.Text.Encoding.UTF8.GetString(decbuff);
        }

        //[DebuggerStepThrough]
        //public static string FormatWith(this string target, params object[] args)
        //{
        //    Check.Argument.IsNotEmpty(target, "target");

        //    return string.Format(CultureInfo.CurrentCulture, target, args);
        //}

        /// <summary>
        /// Fills the entities.
        /// </summary>
        private static void FillEntities()
        {
            _entityTable.Add(160, "&nbsp;");
            _entityTable.Add(161, "&iexcl;");
            _entityTable.Add(162, "&cent;");
            _entityTable.Add(163, "&pound;");
            _entityTable.Add(164, "&curren;");
            _entityTable.Add(165, "&yen;");
            _entityTable.Add(166, "&brvbar;");
            _entityTable.Add(167, "&sect;");
            _entityTable.Add(168, "&uml;");
            _entityTable.Add(169, "&copy;");
            _entityTable.Add(170, "&ordf;");
            _entityTable.Add(171, "&laquo;");
            _entityTable.Add(172, "&not;");
            _entityTable.Add(173, "&shy;");
            _entityTable.Add(174, "&reg;");
            _entityTable.Add(175, "&macr;");
            _entityTable.Add(176, "&deg;");
            _entityTable.Add(177, "&plusmn;");
            _entityTable.Add(178, "&sup2;");
            _entityTable.Add(179, "&sup3;");
            _entityTable.Add(180, "&acute;");
            _entityTable.Add(181, "&micro;");
            _entityTable.Add(182, "&para;");
            _entityTable.Add(183, "&middot;");
            _entityTable.Add(184, "&cedil;");
            _entityTable.Add(185, "&sup1;");
            _entityTable.Add(186, "&ordm;");
            _entityTable.Add(187, "&raquo;");
            _entityTable.Add(188, "&frac14;");
            _entityTable.Add(189, "&frac12;");
            _entityTable.Add(190, "&frac34;");
            _entityTable.Add(191, "&iquest;");
            _entityTable.Add(192, "&Agrave;");
            _entityTable.Add(193, "&Aacute;");
            _entityTable.Add(194, "&Acirc;");
            _entityTable.Add(195, "&Atilde;");
            _entityTable.Add(196, "&Auml;");
            _entityTable.Add(197, "&Aring;");
            _entityTable.Add(198, "&AElig;");
            _entityTable.Add(199, "&Ccedil;");
            _entityTable.Add(200, "&Egrave;");
            _entityTable.Add(201, "&Eacute;");
            _entityTable.Add(202, "&Ecirc;");
            _entityTable.Add(203, "&Euml;");
            _entityTable.Add(204, "&Igrave;");
            _entityTable.Add(205, "&Iacute;");
            _entityTable.Add(206, "&Icirc;");
            _entityTable.Add(207, "&Iuml;");
            _entityTable.Add(208, "&ETH;");
            _entityTable.Add(209, "&Ntilde;");
            _entityTable.Add(210, "&Ograve;");
            _entityTable.Add(211, "&Oacute;");
            _entityTable.Add(212, "&Ocirc;");
            _entityTable.Add(213, "&Otilde;");
            _entityTable.Add(214, "&Ouml;");
            _entityTable.Add(215, "&times;");
            _entityTable.Add(216, "&Oslash;");
            _entityTable.Add(217, "&Ugrave;");
            _entityTable.Add(218, "&Uacute;");
            _entityTable.Add(219, "&Ucirc;");
            _entityTable.Add(220, "&Uuml;");
            _entityTable.Add(221, "&Yacute;");
            _entityTable.Add(222, "&THORN;");
            _entityTable.Add(223, "&szlig;");
            _entityTable.Add(224, "&agrave;");
            _entityTable.Add(225, "&aacute;");
            _entityTable.Add(226, "&acirc;");
            _entityTable.Add(227, "&atilde;");
            _entityTable.Add(228, "&auml;");
            _entityTable.Add(229, "&aring;");
            _entityTable.Add(230, "&aelig;");
            _entityTable.Add(231, "&ccedil;");
            _entityTable.Add(232, "&egrave;");
            _entityTable.Add(233, "&eacute;");
            _entityTable.Add(234, "&ecirc;");
            _entityTable.Add(235, "&euml;");
            _entityTable.Add(236, "&igrave;");
            _entityTable.Add(237, "&iacute;");
            _entityTable.Add(238, "&icirc;");
            _entityTable.Add(239, "&iuml;");
            _entityTable.Add(240, "&eth;");
            _entityTable.Add(241, "&ntilde;");
            _entityTable.Add(242, "&ograve;");
            _entityTable.Add(243, "&oacute;");
            _entityTable.Add(244, "&ocirc;");
            _entityTable.Add(245, "&otilde;");
            _entityTable.Add(246, "&ouml;");
            _entityTable.Add(247, "&divide;");
            _entityTable.Add(248, "&oslash;");
            _entityTable.Add(249, "&ugrave;");
            _entityTable.Add(250, "&uacute;");
            _entityTable.Add(251, "&ucirc;");
            _entityTable.Add(252, "&uuml;");
            _entityTable.Add(253, "&yacute;");
            _entityTable.Add(254, "&thorn;");
            _entityTable.Add(255, "&yuml;");
            _entityTable.Add(402, "&fnof;");
            _entityTable.Add(913, "&Alpha;");
            _entityTable.Add(914, "&Beta;");
            _entityTable.Add(915, "&Gamma;");
            _entityTable.Add(916, "&Delta;");
            _entityTable.Add(917, "&Epsilon;");
            _entityTable.Add(918, "&Zeta;");
            _entityTable.Add(919, "&Eta;");
            _entityTable.Add(920, "&Theta;");
            _entityTable.Add(921, "&Iota;");
            _entityTable.Add(922, "&Kappa;");
            _entityTable.Add(923, "&Lambda;");
            _entityTable.Add(924, "&Mu;");
            _entityTable.Add(925, "&Nu;");
            _entityTable.Add(926, "&Xi;");
            _entityTable.Add(927, "&Omicron;");
            _entityTable.Add(928, "&Pi;");
            _entityTable.Add(929, "&Rho;");
            _entityTable.Add(931, "&Sigma;");
            _entityTable.Add(932, "&Tau;");
            _entityTable.Add(933, "&Upsilon;");
            _entityTable.Add(934, "&Phi;");
            _entityTable.Add(935, "&Chi;");
            _entityTable.Add(936, "&Psi;");
            _entityTable.Add(937, "&Omega;");
            _entityTable.Add(945, "&alpha;");
            _entityTable.Add(946, "&beta;");
            _entityTable.Add(947, "&gamma;");
            _entityTable.Add(948, "&delta;");
            _entityTable.Add(949, "&epsilon;");
            _entityTable.Add(950, "&zeta;");
            _entityTable.Add(951, "&eta;");
            _entityTable.Add(952, "&theta;");
            _entityTable.Add(953, "&iota;");
            _entityTable.Add(954, "&kappa;");
            _entityTable.Add(955, "&lambda;");
            _entityTable.Add(956, "&mu;");
            _entityTable.Add(957, "&nu;");
            _entityTable.Add(958, "&xi;");
            _entityTable.Add(959, "&omicron;");
            _entityTable.Add(960, "&pi;");
            _entityTable.Add(961, "&rho;");
            _entityTable.Add(962, "&sigmaf;");
            _entityTable.Add(963, "&sigma;");
            _entityTable.Add(964, "&tau;");
            _entityTable.Add(965, "&upsilon;");
            _entityTable.Add(966, "&phi;");
            _entityTable.Add(967, "&chi;");
            _entityTable.Add(968, "&psi;");
            _entityTable.Add(969, "&omega;");
            _entityTable.Add(977, "&thetasym;");
            _entityTable.Add(978, "&upsih;");
            _entityTable.Add(982, "&piv;");
            _entityTable.Add(8226, "&bull;");
            _entityTable.Add(8230, "&hellip;");
            _entityTable.Add(8242, "&prime;");
            _entityTable.Add(8243, "&Prime;");
            _entityTable.Add(8254, "&oline;");
            _entityTable.Add(8260, "&frasl;");
            _entityTable.Add(8472, "&weierp;");
            _entityTable.Add(8465, "&image;");
            _entityTable.Add(8476, "&real;");
            _entityTable.Add(8482, "&trade;");
            _entityTable.Add(8501, "&alefsym;");
            _entityTable.Add(8592, "&larr;");
            _entityTable.Add(8593, "&uarr;");
            _entityTable.Add(8594, "&rarr;");
            _entityTable.Add(8595, "&darr;");
            _entityTable.Add(8596, "&harr;");
            _entityTable.Add(8629, "&crarr;");
            _entityTable.Add(8656, "&lArr;");
            _entityTable.Add(8657, "&uArr;");
            _entityTable.Add(8658, "&rArr;");
            _entityTable.Add(8659, "&dArr;");
            _entityTable.Add(8660, "&hArr;");
            _entityTable.Add(8704, "&forall;");
            _entityTable.Add(8706, "&part;");
            _entityTable.Add(8707, "&exist;");
            _entityTable.Add(8709, "&empty;");
            _entityTable.Add(8711, "&nabla;");
            _entityTable.Add(8712, "&isin;");
            _entityTable.Add(8713, "&notin;");
            _entityTable.Add(8715, "&ni;");
            _entityTable.Add(8719, "&prod;");
            _entityTable.Add(8721, "&sum;");
            _entityTable.Add(8722, "&minus;");
            _entityTable.Add(8727, "&lowast;");
            _entityTable.Add(8730, "&radic;");
            _entityTable.Add(8733, "&prop;");
            _entityTable.Add(8734, "&infin;");
            _entityTable.Add(8736, "&ang;");
            _entityTable.Add(8743, "&and;");
            _entityTable.Add(8744, "&or;");
            _entityTable.Add(8745, "&cap;");
            _entityTable.Add(8746, "&cup;");
            _entityTable.Add(8747, "&int;");
            _entityTable.Add(8756, "&there4;");
            _entityTable.Add(8764, "&sim;");
            _entityTable.Add(8773, "&cong;");
            _entityTable.Add(8776, "&asymp;");
            _entityTable.Add(8800, "&ne;");
            _entityTable.Add(8801, "&equiv;");
            _entityTable.Add(8804, "&le;");
            _entityTable.Add(8805, "&ge;");
            _entityTable.Add(8834, "&sub;");
            _entityTable.Add(8835, "&sup;");
            _entityTable.Add(8836, "&nsub;");
            _entityTable.Add(8838, "&sube;");
            _entityTable.Add(8839, "&supe;");
            _entityTable.Add(8853, "&oplus;");
            _entityTable.Add(8855, "&otimes;");
            _entityTable.Add(8869, "&perp;");
            _entityTable.Add(8901, "&sdot;");
            _entityTable.Add(8968, "&lceil;");
            _entityTable.Add(8969, "&rceil;");
            _entityTable.Add(8970, "&lfloor;");
            _entityTable.Add(8971, "&rfloor;");
            _entityTable.Add(9001, "&lang;");
            _entityTable.Add(9002, "&rang;");
            _entityTable.Add(9674, "&loz;");
            _entityTable.Add(9824, "&spades;");
            _entityTable.Add(9827, "&clubs;");
            _entityTable.Add(9829, "&hearts;");
            _entityTable.Add(9830, "&diams;");
            _entityTable.Add(34, "&quot;");
            //_entityTable.Add(38, "&amp;");
            _entityTable.Add(60, "&lt;");
            _entityTable.Add(62, "&gt;");
            _entityTable.Add(338, "&OElig;");
            _entityTable.Add(339, "&oelig;");
            _entityTable.Add(352, "&Scaron;");
            _entityTable.Add(353, "&scaron;");
            _entityTable.Add(376, "&Yuml;");
            _entityTable.Add(710, "&circ;");
            _entityTable.Add(732, "&tilde;");
            _entityTable.Add(8194, "&ensp;");
            _entityTable.Add(8195, "&emsp;");
            _entityTable.Add(8201, "&thinsp;");
            _entityTable.Add(8204, "&zwnj;");
            _entityTable.Add(8205, "&zwj;");
            _entityTable.Add(8206, "&lrm;");
            _entityTable.Add(8207, "&rlm;");
            _entityTable.Add(8211, "&ndash;");
            _entityTable.Add(8212, "&mdash;");
            _entityTable.Add(8216, "&lsquo;");
            _entityTable.Add(8217, "&rsquo;");
            _entityTable.Add(8218, "&sbquo;");
            _entityTable.Add(8220, "&ldquo;");
            _entityTable.Add(8221, "&rdquo;");
            _entityTable.Add(8222, "&bdquo;");
            _entityTable.Add(8224, "&dagger;");
            _entityTable.Add(8225, "&Dagger;");
            _entityTable.Add(8240, "&permil;");
            _entityTable.Add(8249, "&lsaquo;");
            _entityTable.Add(8250, "&rsaquo;");
            _entityTable.Add(8364, "&euro;");
        }

        /// <summary>
        /// Converts US State Name to it's two-character abbreviation. Returns null if the state name was not found.
        /// </summary>
        /// <param name="stateName">US State Name (ie Texas)</param>
        /// <returns></returns>
        public static string USStateNameToAbbrev(string stateName)
        {
            stateName = stateName.ToUpper();
            foreach (KeyValuePair<string, string> key in _USStateTable)
            {
                if (stateName == key.Key)
                    return key.Value;
            }
            return null;
        }

        /// <summary>
        /// Converts a two-character US State Abbreviation to it's official Name Returns null if the abbreviation was not found.
        /// </summary>
        /// <param name="stateAbbrev">US State Name (ie Texas)</param>
        /// <returns></returns>
        public static string USStateAbbrevToName(string stateAbbrev)
        {
            stateAbbrev = stateAbbrev.ToUpper();
            foreach (KeyValuePair<string, string> key in _USStateTable)
            {
                if (stateAbbrev == key.Value)
                    return key.Key;
            }
            return null;
        }

        /// <summary>
        /// Fills the US States.
        /// </summary>
        private static void FillUSStates()
        {
            _USStateTable.Add("ALABAMA", "AL");
            _USStateTable.Add("ALASKA", "AK");
            _USStateTable.Add("AMERICAN SAMOA", "AS");
            _USStateTable.Add("ARIZONA ", "AZ");
            _USStateTable.Add("ARKANSAS", "AR");
            _USStateTable.Add("CALIFORNIA ", "CA");
            _USStateTable.Add("COLORADO ", "CO");
            _USStateTable.Add("CONNECTICUT", "CT");
            _USStateTable.Add("DELAWARE", "DE");
            _USStateTable.Add("DISTRICT OF COLUMBIA", "DC");
            _USStateTable.Add("FEDERATED STATES OF MICRONESIA", "FM");
            _USStateTable.Add("FLORIDA", "FL");
            _USStateTable.Add("GEORGIA", "GA");
            _USStateTable.Add("GUAM ", "GU");
            _USStateTable.Add("HAWAII", "HI");
            _USStateTable.Add("IDAHO", "ID");
            _USStateTable.Add("ILLINOIS", "IL");
            _USStateTable.Add("INDIANA", "IN");
            _USStateTable.Add("IOWA", "IA");
            _USStateTable.Add("KANSAS", "KS");
            _USStateTable.Add("KENTUCKY", "KY");
            _USStateTable.Add("LOUISIANA", "LA");
            _USStateTable.Add("MAINE", "ME");
            _USStateTable.Add("MARSHALL ISLANDS", "MH");
            _USStateTable.Add("MARYLAND", "MD");
            _USStateTable.Add("MASSACHUSETTS", "MA");
            _USStateTable.Add("MICHIGAN", "MI");
            _USStateTable.Add("MINNESOTA", "MN");
            _USStateTable.Add("MISSISSIPPI", "MS");
            _USStateTable.Add("MISSOURI", "MO");
            _USStateTable.Add("MONTANA", "MT");
            _USStateTable.Add("NEBRASKA", "NE");
            _USStateTable.Add("NEVADA", "NV");
            _USStateTable.Add("NEW HAMPSHIRE", "NH");
            _USStateTable.Add("NEW JERSEY", "NJ");
            _USStateTable.Add("NEW MEXICO", "NM");
            _USStateTable.Add("NEW YORK", "NY");
            _USStateTable.Add("NORTH CAROLINA", "NC");
            _USStateTable.Add("NORTH DAKOTA", "ND");
            _USStateTable.Add("NORTHERN MARIANA ISLANDS", "MP");
            _USStateTable.Add("OHIO", "OH");
            _USStateTable.Add("OKLAHOMA", "OK");
            _USStateTable.Add("OREGON", "OR");
            _USStateTable.Add("PALAU", "PW");
            _USStateTable.Add("PENNSYLVANIA", "PA");
            _USStateTable.Add("PUERTO RICO", "PR");
            _USStateTable.Add("RHODE ISLAND", "RI");
            _USStateTable.Add("SOUTH CAROLINA", "SC");
            _USStateTable.Add("SOUTH DAKOTA", "SD");
            _USStateTable.Add("TENNESSEE", "TN");
            _USStateTable.Add("TEXAS", "TX");
            _USStateTable.Add("UTAH", "UT");
            _USStateTable.Add("VERMONT", "VT");
            _USStateTable.Add("VIRGIN ISLANDS", "VI");
            _USStateTable.Add("VIRGINIA ", "VA");
            _USStateTable.Add("WASHINGTON", "WA");
            _USStateTable.Add("WEST VIRGINIA", "WV");
            _USStateTable.Add("WISCONSIN", "WI");
            _USStateTable.Add("WYOMING", "WY");
        }

        //将文本的换行符转换为HTML的换行符
        public static string HtmlNewline(string inputText)
        {
            if (string.IsNullOrEmpty(inputText))
            {
                return string.Empty;
            }
            if (inputText.Contains(Environment.NewLine))
            {
                inputText = inputText.Replace(Environment.NewLine, "<br />");
            }
            //当用js提交时，换行符为“\n”
            if (inputText.Contains("\n"))
            {
                inputText = inputText.Replace(Environment.NewLine, "\n");
            }
            return inputText;
        }

        /// <summary>
        /// 清除网页中详细说明的js代码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string RemoveScript(string str)
        {
            str = str.ToLower();
            int length = str.Length;

            ArrayList arr1 = new ArrayList();
            ArrayList arr2 = new ArrayList();

            for (int i = 0; i < length - 6; i++)
            {
                if (str[i].ToString() == "<")
                {
                    if (str[i + 1].ToString() == "s" && str[i + 2].ToString() == "c" && str[i + 3].ToString() == "r" &&
                        str[i + 4].ToString() == "i" && str[i + 5].ToString() == "p" && str[i + 6].ToString() == "t")
                    {
                        arr1.Add(i);
                        for (int j = i + 8; j < length - 6; j++)
                        {
                            if (str[j].ToString() == "<")
                            {
                                if (str[j + 1].ToString() == "/" && str[j + 2].ToString() == "s" && str[j + 3].ToString() == "c" && str[j + 4].ToString() == "r" &&
                                     str[j + 5].ToString() == "i" && str[j + 6].ToString() == "p" && str[j + 7].ToString() == "t")
                                {
                                    arr2.Add(j + 9);
                                    i = j + 9;
                                    break;
                                }
                            }
                        }//找邻近的"</script"位置
                    }
                }
            }//逐个查看“<script”的开始位置

            string NoscriptStr = "";
            if (arr1.Count == arr2.Count)
            {
                int arrlen = arr1.Count;
                int subleft = 0;
                int subright = 0;
                string substr = "";

                for (int k = 0; k < arrlen; k++)
                {
                    subright = Convert.ToInt32(arr1[k].ToString());
                    substr = str.Substring(subleft, subright - subleft);
                    NoscriptStr = NoscriptStr + substr;
                    subleft = Convert.ToInt32(arr2[k].ToString());
                }
                substr = str.Substring(subleft, length - subleft);
                NoscriptStr = NoscriptStr + substr;
            }

            return NoscriptStr;
        }

        /// <summary>
        /// 返回唯一的随机串
        /// </summary>
        /// <returns></returns>
        public static string RandomString()
        {
            return (Guid.NewGuid().ToString() + Guid.NewGuid().ToString()).Replace("-", "");
        }

        /// <summary>
        /// 获取当前网站启动的物理路径
        /// </summary>
        /// <returns></returns>
        public static string WebsiteAppPath()
        {
            return HttpContext.Current.Request.PhysicalApplicationPath;
        }


    }
}